package ExperimentSix.SplitFile;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;

public class FileUploadClient {
    public static void main(String[] args) throws IOException {
//        服务端地址
        String serverIP = "localhost";
//        端口
        int serverPort = 62483;
        String filePath = "E:\\Java\\JavaExperimentOne\\students_sent_file.txt"; // 文件路径，请替换为实际路径
        int chunkSize =1024*1024;//1MB

        try (Socket socket = new Socket(serverIP, serverPort);
             FileInputStream fis = new FileInputStream(filePath);
             DataOutputStream dos = new DataOutputStream(socket.getOutputStream())) {

            byte[] buffer = new byte[chunkSize];
            int chunkNum = 0;
            CountDownLatch latch = new CountDownLatch(1); // 初始化一个CountDownLatch

            while (true) {
                int readBytes = fis.read(buffer);
                if (readBytes <= 0) break; // 当read返回-1时，表示文件读取完毕
                final int finalChunkNum = chunkNum++;

                Thread uploadThread = new Thread(() -> {
                    try {
                        dos.writeInt(finalChunkNum);
                        dos.writeInt(readBytes);
                        dos.write(buffer, 0, readBytes);
                        System.out.println("分片 " + finalChunkNum + " 被发送.");
                    } catch (IOException e) {
                        System.err.println("Error uploading chunk " + finalChunkNum + ": " + e.getMessage());
                    } finally {
                        latch.countDown(); // 每个线程完成上传后countDown
                    }
                });
                uploadThread.start();
            }

            // 等待所有分片上传完成
            latch.await(); // 主线程等待所有上传线程完成
            socket.shutdownOutput(); // 所有数据发送完毕后关闭输出流，但保持连接以便服务器端确认

        } catch (InterruptedException | IOException e) {
            System.err.println("Client error: " + e.getMessage());
        }
    }
}